<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Menu extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'name',
        'icon',
        'path',
        'component',
        'description',
        'status',
        'is_visible',
        'sort_order',
    ];

    protected $casts = [
        'is_visible' => 'boolean',
    ];

    /**
     * 获取菜单下的所有功能
     */
    public function functions(): HasMany
    {
        return $this->hasMany(FunctionModel::class)->orderBy('sort_order');
    }

    /**
     * 获取菜单的核心功能
     */
    public function coreFunctions(): HasMany
    {
        return $this->hasMany(FunctionModel::class)->where('level', 'core')->orderBy('sort_order');
    }

    /**
     * 获取菜单的可选功能
     */
    public function optionalFunctions(): HasMany
    {
        return $this->hasMany(FunctionModel::class)->where('level', 'optional')->orderBy('sort_order');
    }

    /**
     * 检查菜单是否启用
     */
    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    /**
     * 检查菜单是否可见
     */
    public function isVisible(): bool
    {
        return $this->is_visible;
    }

    /**
     * 获取状态标签
     */
    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            'active' => '启用',
            'inactive' => '禁用',
            default => $this->status,
        };
    }

    /**
     * 获取可见性标签
     */
    public function getVisibilityLabelAttribute(): string
    {
        return $this->is_visible ? '可见' : '隐藏';
    }

    /**
     * 检查用户是否有权限访问此菜单
     */
    public function userCanAccess(User $user): bool
    {
        if (!$this->isActive() || !$this->isVisible()) {
            return false;
        }

        // 检查用户是否为超级管理员
        if ($user->hasRole('super_admin')) {
            return true;
        }

        // 获取用户的所有功能ID
        $functionIds = $user->roles()
            ->where('roles.status', 'active')
            ->join('role_function_permissions', 'roles.id', '=', 'role_function_permissions.role_id')
            ->pluck('role_function_permissions.function_id')
            ->unique()
            ->toArray();

        if (empty($functionIds)) {
            return false;
        }

        // 检查用户是否有该菜单的任一功能权限
        return $this->functions()
            ->where('status', 'active')
            ->whereIn('id', $functionIds)
            ->exists();
    }

    /**
     * 获取用户可访问的菜单列表
     */
    public static function getUserMenus(User $user)
    {
        // 获取用户的所有功能ID
        $functionIds = $user->roles()
            ->where('roles.status', 'active')
            ->join('role_function_permissions', 'roles.id', '=', 'role_function_permissions.role_id')
            ->pluck('role_function_permissions.function_id')
            ->unique()
            ->toArray();

        if (empty($functionIds)) {
            return collect();
        }

        return static::where('status', 'active')
            ->where('is_visible', true)
            ->whereHas('functions', function ($query) use ($functionIds) {
                $query->where('status', 'active')
                    ->whereIn('id', $functionIds);
            })
            ->with(['functions' => function ($query) use ($functionIds) {
                $query->where('status', 'active')
                    ->whereIn('id', $functionIds)
                    ->orderBy('sort_order');
            }])
            ->orderBy('sort_order')
            ->get();
    }

    /**
     * 获取用户有权限的功能列表
     */
    public function getUserFunctions(User $user)
    {
        // 获取用户的所有功能ID
        $functionIds = $user->roles()
            ->where('roles.status', 'active')
            ->join('role_function_permissions', 'roles.id', '=', 'role_function_permissions.role_id')
            ->pluck('role_function_permissions.function_id')
            ->unique()
            ->toArray();

        if (empty($functionIds)) {
            return collect();
        }

        return $this->functions()
            ->where('status', 'active')
            ->whereIn('id', $functionIds)
            ->orderBy('sort_order')
            ->get();
    }

    /**
     * 作用域：活跃菜单
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * 作用域：可见菜单
     */
    public function scopeVisible($query)
    {
        return $query->where('is_visible', true);
    }

    /**
     * 作用域：按编码查找
     */
    public function scopeByCode($query, string $code)
    {
        return $query->where('code', $code);
    }
}
